package com.guchenbo.example.dubbo.cluster;

import com.guchenbo.example.dubbo.template.InvokerTemplate;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;

import java.util.List;

public class ClusterInvoker<T> extends InvokerTemplate<T> {

  private Directory directory;
  private LoadBalance loadBalance;

  public <T> ClusterInvoker(URL url, Class<T> type, Directory<T> directory) {
    super(type, url);
    this.directory = directory;
    this.loadBalance = new GcbLoadBalance();
  }

  @Override
  protected Result doInvoke(Invocation invocation) throws RpcException {
    // list all
    List<Invoker<T>> invokers = directory.list(invocation);
    // select one by LoadBalance
    Invoker invoker = select(invokers, getUrl(), invocation);
    System.out.println("use invoker " + invoker);
    return invoker.invoke(invocation);
  }

  private Invoker select(List<Invoker<T>> invokers, URL url,
      Invocation invocation) {
    return loadBalance.select(invokers, url, invocation);
  }

}
